package com.example.family_sec;

import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.BottomSheetDialogFragment;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.example.family_sec.service.ProxyMessage;

import java.lang.reflect.Field;

import static android.content.Context.MODE_PRIVATE;

public class SettingFragment extends BottomSheetDialogFragment {



 private static final String TAG = "FullSheetDialogFrag";
    // 向下偏移
    private int topOffset = 0;

    //
    private  int lastX;
    private  int lastY;

    private BottomSheetBehavior<FrameLayout> behavior;
    private BottomSheetDialog dialog;


    public SettingFragment() {
        super();

    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return super.onCreateDialog(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // return super.onCreateView(inflater, container, savedInstanceState);

        Log.i(TAG, "onCreateView");

        View view = inflater.inflate(R.layout.layout_setting_fragment, container);



        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()){


                    case MotionEvent.ACTION_DOWN:{
                        lastX = (int) event.getRawX();
                        lastY = (int) event.getRawY();

                        return true;
                    }

                    case MotionEvent.ACTION_MOVE:{


                        return true;


                    }
                }

                return false;
            }
        });





        return view;
    }





    @Override
    public void onStart() {
        super.onStart();

        // get
        dialog = (BottomSheetDialog) getDialog();

        dialog.setCanceledOnTouchOutside(true);

        FrameLayout bottomSheet = dialog.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet);

        CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) bottomSheet.getLayoutParams();

        // 设置高度
        layoutParams.height = getHeight();


        behavior = BottomSheetBehavior.from(bottomSheet);



        // 设置为伸展的状态
        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);

//        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
//            @Override
//            public void onStateChanged(@NonNull View bottomSheet, int newState) {
//
//            }
//
//            @Override
//            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
//
//            }
//        });
    }


    // fragment 的高度 计算素质为
    // 屏幕总的高度减去 状态栏 - 标题栏的高度, 没有top margin
    private int getHeight() {


        int height = 1920;


        if (getContext() != null) {
            WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            Point point = new Point();
            if (wm != null) {
                // 使用Point已经减去了状态栏高度
                wm.getDefaultDisplay().getSize(point);
                height = point.y - getTopOffset();

                int identifier = getResources().getIdentifier("status_bar_height", "dimen",
                        "android");


                TypedValue tv = new TypedValue();
                int actionBarHeight = 0;

                //  getContext().getTheme().resolveAttribute()

                // 获取action bar 的高度
                if (getContext().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
                    actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getContext().getResources().getDisplayMetrics());

                    Log.i(TAG, "actionBarHeight " + actionBarHeight + "    getStatusBarHeight() " + getStatusBarHeight());
                }


                // 高度 == 总的屏幕的高度 -actionBar高度 - 偏移量的高度 -  状态栏的高度 ;
                height = point.y - actionBarHeight - topOffset - getStatusBarHeight();


            }
        }


        return height;
    }

    public int getTopOffset() {
        return topOffset;
    }

    public void setTopOffset(int topOffset) {
        this.topOffset = topOffset;
    }

    public BottomSheetBehavior<FrameLayout> getBehavior() {
        return behavior;
    }


    // 获取状态栏的高度
    // 获取高度失败,默认返回 75
    private int getStatusBarHeight() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            Log.d(TAG, "get status bar height fail");
            e1.printStackTrace();
            return 75;
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        Switch sw_buzzer =view. findViewById(R.id.sw_buzzer);
        Switch sw_notification = view . findViewById(R.id.sw_notification);

        Settings settings = new Settings();

        SharedPreferences sp =view.getContext(). getSharedPreferences("settings", MODE_PRIVATE);
        boolean buzzer = sp.getBoolean("buzzer", false);
        boolean notification = sp.getBoolean("notification", false);
        settings.setBuzzer(buzzer);
        settings.setUnNotification(notification);

        // ...
        //
        sw_buzzer.setChecked(buzzer);
        sw_notification.setChecked(notification);

        // 关闭开启蜂鸣器的操作
        sw_buzzer.setOnCheckedChangeListener((buttonView, isChecked) -> {

            Toast.makeText(buttonView.getContext(), "checked " + isChecked, Toast.LENGTH_SHORT).show();

            sp.edit().putBoolean("buzzer",isChecked).apply();
            // todo ....提交服务器用户关闭蜂鸣器的警报的异常信息处理.

            FragmentActivity activity = getActivity();

            try {
                MainActivity mainActivity = (MainActivity) activity;
                ProxyMessage proxyMessage = new ProxyMessage();
                proxyMessage.setMsg("蜂鸣器工作参数设置........");
                // 关闭蜂鸣器
                if (isChecked ) {
                    proxyMessage.setCode(ProxyMessage.App_2_Pr_Close_Buzzer);
                } else {
                    // 打开蜂鸣器
                    proxyMessage.setCode(ProxyMessage.App_2_Pr_Open_Buzzer);
                }

                String phone = buttonView.getContext().getSharedPreferences("lastLogin", MODE_PRIVATE).getString("phone", "");

                LogUtil.d(TAG,"set");
               // proxyMessage.setMsg(phone);



                boolean b = mainActivity.getWsBinder().sendText(JSON.toJSONString(proxyMessage));
                if (!b ){
                    mainActivity.getWsBinder().reConnect();
                }
            }catch (ClassCastException e ){
                throw  new ClassCastException("....");
            }


        });

        sw_notification.setOnCheckedChangeListener(((buttonView, isChecked) -> {
            sp.edit().putBoolean("notification",isChecked).apply();
        }));
    }
}
